use crate::models::product_categories::{self, CreateParams, UpdateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/product-categories", post(create))
        .route("/product-categories/:id", get(get_by_id))
        .route("/product-categories/:id", post(update))
        .route("/product-categories/:id/delete", post(delete))
        .route(
            "/product-categories/by-product/:product_id",
            get(get_by_product),
        )
        .route(
            "/product-categories/by-category/:category_id",
            get(get_by_category),
        )
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let product_category = product_categories::Model::create(&state.db, params).await?;
    format::json(product_category)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let product_category = product_categories::Model::find_by_id(&state.db, &id).await?;
    format::json(product_category)
}

async fn update(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
    Json(params): Json<UpdateParams>,
) -> Result<Response> {
    let product_category = product_categories::Model::update_by_id(&state.db, &id, params).await?;
    format::json(product_category)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    product_categories::Model::delete_by_id(&state.db, &id).await?;
    format::json(())
}

async fn get_by_product(
    State(state): State<AppContext>,
    axum::extract::Path(product_id): axum::extract::Path<u64>,
) -> Result<Response> {
    let product_categories =
        product_categories::Model::find_by_product(&state.db, product_id).await?;
    format::json(product_categories)
}

async fn get_by_category(
    State(state): State<AppContext>,
    axum::extract::Path(category_id): axum::extract::Path<u64>,
) -> Result<Response> {
    let product_categories =
        product_categories::Model::find_by_category(&state.db, category_id).await?;
    format::json(product_categories)
}
